package com.ymt.bpm.service.remind;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.ymt.bpm.dao.remind.PMessageMapper;
import com.ymt.bpm.dao.remind.PNotifyMapper;
import com.ymt.bpm.model.PNotify;
import com.ymt.util.DateUtil;

@Service
public class NotifyShedule {

	private Logger log = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private PNotifyMapper nDao;
	@Autowired
	private PMessageMapper mDao;
	@Autowired
	private SendMessageService ns;
	
	@Scheduled(cron = "0/10 * * * * ? ")//每30秒扫描一次
	public void taskShedule(){
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date stime = new Date();
		if (log.isTraceEnabled()) {
			log.trace("Schedule ID: "+Thread.currentThread().getId()+" ==== triggered at "+sdf.format(stime));
		}

		List<PNotify> notifies = nDao.selectByStatus("0", 10, DateUtil.getGMTDate());
		
		if (notifies==null || notifies.size()==0) {
			if (log.isTraceEnabled()) {
				log.trace("No notifies found.");
			}
		} else {
			for(PNotify notify : notifies){
				
				if ("1".equals(notify.gettType()) || "0".equals(notify.gettType())) {//新任务或到期任务提醒
					//检查任务是否存在
					int rs = nDao.isTodoExist(notify.getTiId());
					if (rs==0) {//任务不存在，可能已完成
						nDao.deleteByPrimaryKey(notify.getId());
						continue;
					}
				}
				
				try {
					//发送
					ns.notify(notify);
					//成功后删除
					nDao.deleteByPrimaryKey(notify.getId());
				}catch (Exception e) {
					log.error(notify+" send failure！！");
					e.printStackTrace();
					notify.setStatus("2");	//标记为未发送成功
					nDao.updateByPrimaryKey(notify);
				}
			}
		}
		
		Date etime = new Date();
		if (log.isTraceEnabled()) {
			log.trace("线程ID: " + Thread.currentThread().getId() + "====lasted milliseconds " + (etime.getTime() - stime.getTime()));
		}
	}
	
}
